package com.game.base.monitor.permission;

import android.annotation.TargetApi;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import com.game.base.utils.log.Logger;

import java.util.List;

/**
 * 使用数据权限控制[https://www.jianshu.com/p/3b6bcf9cec67]
 * Created by Su on 2019/6/4.
 */
public class AppUsageUtil {
    /**
     * 检测是否成功授权
     */
    public static boolean checkUsageStateAccessPermission(Context context) {
        boolean result = AppUsageUtil.checkAppUsagePermission(context);
        if (!result) {
            AppUsageUtil.requestAppUsagePermission(context);
        }
        return result;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    private static boolean checkAppUsagePermission(Context context) {
        UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        if (usageStatsManager == null) {
            return false;
        }
        long currentTime = System.currentTimeMillis();
        // try to get app usage state in last 1 min
        List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, currentTime - 60 * 1000, currentTime);
        return stats.size() != 0;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static void requestAppUsagePermission(Context context) {
        Intent intent = new Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Logger.i("Start usage access settings activity fail!");
        }
    }
}
